def shell(cmd, cwd=None, timeout=None, shell=True):
    import datetime
    import subprocess
    import time

    if timeout:
        end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)

    sub = subprocess.Popen(cmd, cwd=cwd, stdin=subprocess.PIPE, shell=shell, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)

    while sub.poll() is None:
        time.sleep(0.1)
        if timeout:
            if end_time <= datetime.datetime.now():
                raise Exception("Timeout：%s" % cmd)

    return sub.communicate()
